package com.luodim.dialogtest;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * 简易自定义dialog view，不具备通用性，过渡阶段使用，后续废弃
 * Created by luodi on 2017/7/7.
 */

public class DialogView extends RelativeLayout implements View.OnClickListener{
    public static final int ONE_PIC = 1; // 只有一张海报图的dialog类型
    public static final int TWO_PIC = 2; // 有一张海报图及一张红包图的dialog类型

    //-------------------可点击view的tag类型---------------------
    public static final int CLOSE = 1; // 关闭按钮
    public static final int WE_CHAT = 2; // 微信
    public static final int WE_CIRCLE = 3; // 朋友圈
    public static final int QQ = 4; // QQ
    public static final int QQ_ZONE = 5; // QQ空间
    public static final int BOOK_POSTER = 6; // 分享图书封面
    public static final int RED_PACKET = 7; // 红包

    //-------------------布局规则类型----------------------------------
    private static final int ALIGN_L_T = 1; // 与基准参考view的left及top对齐
    private static final int ALIGN_L_B = 2; // 与基准参考view的left及bottom对齐
    private static final int ALIGN_R_T = 3; // 与基准参考view的right及top对齐
    private static final int ALIGN_R_B = 4; // 与基准参考view的right及bottom对齐
    private static final int ALIGN_T = 5; // 与基准参考view的top对齐
    private static final int CENTER_IN_PARENT = 7; // 在父控件水平垂直居中

    private Context mContext;
    private ImageView mMidImg;
    private ImageView mClose;
    private ImageView mDialogBg;
    private TextView mTitle;
    private ImageView mRect;
    private ImageView mWeChat;
    private ImageView mFriends;
    private ImageView mQQ;
    private ImageView mQQSpace;
    private ImageView mRectL;
    private ImageView mRectR;
    private ImageView mContentL;
    private ImageView mContentR;
    private ImageView mLine;
    private int mBaseId;
    private OnDialogClickListener mListener;
    private TextView mStep1;
    private TextView mStep2;
    private TextView mShareBookCount;
    private TextView mShareRedPacketCount;
    private View mContentView;
    private int mCurType;
    private int mPosterType;
    private ImageView mSelectedL;
    private ImageView mSelectedR;
    private static int mOri = -1;
    private static DisplayMetrics mMetrics;

    public DialogView(Context context) {
        this(context, null);
    }

    public DialogView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DialogView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    public void initView(int type) {
        if (mCurType == type && mContentView != null) return;
        mCurType = type;
        removeAllViews();
        mPosterType = BOOK_POSTER;
        switch (type) {
            case ONE_PIC:
                mContentView = View.inflate(mContext, R.layout.dialog_one_poster, this);
                mMidImg = (ImageView) mContentView.findViewById(R.id.img_content);
                mClose = (ImageView) mContentView.findViewById(R.id.img_close);
                mDialogBg = (ImageView) mContentView.findViewById(R.id.dialog_bg);
                mTitle = (TextView) mContentView.findViewById(R.id.tv_title);
                mRect = (ImageView) mContentView.findViewById(R.id.poster_rect);
                mWeChat = (ImageView) mContentView.findViewById(R.id.img_wechat);
                mFriends = (ImageView) mContentView.findViewById(R.id.img_friends);
                mQQ = (ImageView) mContentView.findViewById(R.id.img_qq);
                mQQSpace = (ImageView) mContentView.findViewById(R.id.img_qq_space);
                mLine = (ImageView) mContentView.findViewById(R.id.img_line);
                mBaseId = R.id.dialog_bg;
                setClickListener(mClose, mWeChat, mFriends, mQQ, mQQSpace);
                break;
            case TWO_PIC:
                mContentView = View.inflate(mContext, R.layout.dialog_two_posters, this);
                mClose = (ImageView) mContentView.findViewById(R.id.img_close_2);
                mDialogBg = (ImageView) mContentView.findViewById(R.id.dialog_bg_2);
                mTitle = (TextView) mContentView.findViewById(R.id.tv_title_2);
                mRectL = (ImageView) mContentView.findViewById(R.id.img_rect_l);
                mRectR = (ImageView) mContentView.findViewById(R.id.img_rect_r);
                mContentL = (ImageView) mContentView.findViewById(R.id.img_content_l);
                mContentR = (ImageView) mContentView.findViewById(R.id.img_content_r);
                mStep1 = (TextView) mContentView.findViewById(R.id.tv_step_1);
                mStep2 = (TextView) mContentView.findViewById(R.id.tv_step_2);
                mShareBookCount = (TextView) mContentView.findViewById(R.id.tv_share_book);
                mShareRedPacketCount = (TextView) mContentView.findViewById(R.id.tv_share_rp);
                mSelectedL = (ImageView) mContentView.findViewById(R.id.img_selected_l);
                mSelectedR = (ImageView) mContentView.findViewById(R.id.img_selected_r);
                mWeChat = (ImageView) mContentView.findViewById(R.id.img_wechat_2);
                mFriends = (ImageView) mContentView.findViewById(R.id.img_friends_2);
                mQQ = (ImageView) mContentView.findViewById(R.id.img_qq_2);
                mQQSpace = (ImageView) mContentView.findViewById(R.id.img_qq_space_2);
                mLine = (ImageView) mContentView.findViewById(R.id.img_line_2);
                mBaseId = R.id.dialog_bg_2;
                setClickListener(mRectL, mRectR, mClose, mWeChat, mFriends, mQQ, mQQSpace);
                break;
        }
        initPosition(type);
    }

    private void resetSelected() {
        if (mRectL == null || mRectR == null || mSelectedL == null || mSelectedR == null) return;
        mRectL.setImageResource(R.drawable.dialog_dash_rect);
        mRectR.setImageResource(R.drawable.dialog_dash_rect);
        mSelectedL.setVisibility(View.INVISIBLE);
        mSelectedR.setVisibility(View.INVISIBLE);
    }

    private void setClickListener(View... views) {
        for (View v : views) {
            if (v != null) {
                v.setOnClickListener(this);
            }
        }
    }

    private void initPosition(int type) {
        this.setVisibility(View.INVISIBLE);

        // 设备宽高
        int devWidth = getDevicesInfo(mContext).widthPixels;
        int devHeight = getDevicesInfo(mContext).heightPixels;

        // 基于比例生成的dialog背景的宽高
        int dialogBgW = Math.round(devWidth * 0.6f);
        int dialogBgH = Math.round(devHeight * 0.7f);

        int rectsMarginLR = Math.round(dialogBgW * 0.042f);
        int rectsMarginT = Math.round(dialogBgH * 0.23f);
        int contentsMarginLR = Math.round(dialogBgW * 0.17f);
        int contentsMarginT = Math.round(dialogBgH * 0.345f);

        // 关闭按钮margin right and top
        int closeBtnMarginRT = Math.round(dialogBgW * 0.025f);

        // 标题的margin top数值
        int titleMarginT = Math.round(dialogBgH * 0.1f);

        // 分享图标基本尺寸
        int baseSize = Math.round(dialogBgW * 0.069f);
        // 分享图标left基准margin值
        int shareMarginL = Math.round(dialogBgW * 0.19f);
        // 分享图标top基准margin值
        int shareMarginB = Math.round(dialogBgH * 0.036f);
        // 分享图标间距
        int shareGap = Math.round(dialogBgW * 0.18f);

        // 分隔线margin bottom数值
        int lineMarginB = Math.round(dialogBgH * 0.17f);

        // 圆角矩形背景
        adjustLayout(mDialogBg, dialogBgW, dialogBgH, getMarinParams(0, devHeight * 0.12f, devWidth * 0.2f, 0), CENTER_IN_PARENT);

        // 关闭按钮
        mClose.setTag(CLOSE);
        adjustLayout(mClose, (int) (dialogBgW * 0.097f), (int ) (dialogBgW * 0.097f), getMarinParams(0, -closeBtnMarginRT, -closeBtnMarginRT, 0), ALIGN_R_T);

        // 标题
        AssetManager mgr = getContext().getApplicationContext().getAssets();
        Typeface typeFace = Typeface.createFromAsset(mgr, "fonts/DFPHAIBAOW12-GB.TTF");
        mTitle.setTypeface(typeFace);
        mTitle.setText("分享这本好看的动画书给小伙伴吧");
        mTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, dialogBgH * 0.075f);
        adjustLayout(mTitle, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, getMarinParams(0, titleMarginT, 0, 0), ALIGN_T);

        // 分隔线
        adjustLayout(mLine, dialogBgW, 1, getMarinParams(0, 0, 0, lineMarginB), ALIGN_L_B);
        // share部分的设置
        setSharePart(baseSize, shareMarginL, shareMarginB, shareGap);

        if (type == ONE_PIC) {
            // 圆角矩形点画线
            adjustLayout(mRect, (int) (dialogBgW * 0.27f), (int) (dialogBgH * 0.5f), getMarinParams(0, 0, 0, 0), CENTER_IN_PARENT);

            // 单幅海报居中
            // TODO: 2017/7/7 test code will be removed later, need to verify the possible of imageView
            mMidImg.setImageResource(R.drawable.owl);
            adjustLayout(mMidImg, (int) (dialogBgW * 0.23f), (int) (dialogBgH * 0.45f), getMarinParams(0, 0, 0, 0), CENTER_IN_PARENT);
        } else if (type == TWO_PIC) {
            // 圆角矩形点画线
            mRectL.setTag(BOOK_POSTER);
            mRectR.setTag(RED_PACKET);
            adjustLayout(mRectL, (int) (dialogBgW * 0.44f), (int) (dialogBgH * 0.55f), getMarinParams(rectsMarginLR, rectsMarginT, 0, 0), ALIGN_L_T);
            adjustLayout(mRectR, (int) (dialogBgW * 0.44f), (int) (dialogBgH * 0.55f), getMarinParams(0, rectsMarginT, rectsMarginLR, 0), ALIGN_R_T);

            // 海报及红包
            // TODO: 2017/7/7 test code will be removed later
            mContentL.setImageResource(R.drawable.owl);
            mContentR.setImageResource(R.drawable.fenxiang_hongbao_736h);
            adjustLayout(mContentL, (int) (dialogBgW * 0.18f), (int) (dialogBgH * 0.35f),
                    getMarinParams(contentsMarginLR, contentsMarginT, 0, 0), ALIGN_L_T);
            adjustLayout(mContentR, (int) (dialogBgW * 0.18f), (int) (dialogBgH * 0.35f),
                    getMarinParams(0, contentsMarginT, contentsMarginLR, 0), ALIGN_R_T);

            // 选中勾
            mSelectedL.setImageResource(R.drawable.fenxiang_button_xuanzhong_736h);
            adjustLayout(mSelectedL, (int) (dialogBgW * 0.0375f), (int) (dialogBgW * 0.0375f),
                    getMarinParams(dialogBgW * 0.054f, dialogBgH * 0.25f, 0, 0), ALIGN_L_T);
            mSelectedR.setImageResource(R.drawable.fenxiang_button_xuanzhong_736h);
            adjustLayout(mSelectedR, (int) (dialogBgW * 0.0375f), (int) (dialogBgW * 0.0375f),
                    getMarinParams(dialogBgW * 0.53f, dialogBgH * 0.25f, 0, 0), ALIGN_L_T);
            mSelectedL.setVisibility(View.INVISIBLE);
            mSelectedR.setVisibility(View.INVISIBLE);

            addShareText((int) (dialogBgW * 0.44f), dialogBgW, dialogBgH);

        }
    }

    private void addShareText(int rectW, int dialogBgW, int dialogBgH) {
        mStep1.setTextSize(TypedValue.COMPLEX_UNIT_PX, dialogBgH * 0.04f);
        mStep2.setTextSize(TypedValue.COMPLEX_UNIT_PX, dialogBgH * 0.04f);
        mShareBookCount.setTextSize(TypedValue.COMPLEX_UNIT_PX, dialogBgH * 0.036f);
        mShareRedPacketCount.setTextSize(TypedValue.COMPLEX_UNIT_PX, dialogBgH * 0.036f);

        mStep1.setText("① 请别人看书");
        mStep2.setText("② 送购书红包");
        mShareBookCount.setText("3个动画书借阅名额分享");
        mShareRedPacketCount.setText("10个购书红包待分享");

        adjustLayout(mStep1, rectW, LayoutParams.WRAP_CONTENT, getMarinParams(dialogBgW * 0.04f, dialogBgH * 0.26f, 0, 0), ALIGN_L_T);
        adjustLayout(mStep2, rectW, LayoutParams.WRAP_CONTENT, getMarinParams(0, dialogBgH * 0.26f, dialogBgW * 0.04f, 0), ALIGN_R_T);
        adjustLayout(mShareBookCount, rectW, LayoutParams.WRAP_CONTENT, getMarinParams(dialogBgW * 0.04f, 0, 0, dialogBgH * 0.24f), ALIGN_L_B);
        adjustLayout(mShareRedPacketCount, rectW, LayoutParams.WRAP_CONTENT, getMarinParams(0, 0, dialogBgW * 0.04f, dialogBgH * 0.24f), ALIGN_R_B);

        setTextColorSpan(mShareBookCount, mShareBookCount.getText().toString());
        setTextColorSpan(mShareRedPacketCount, mShareRedPacketCount.getText().toString());
    }

    private void setTextColorSpan(TextView tv, String str) {
        int firstEndIndex = str.indexOf("个") + 1;
        if (firstEndIndex < 0) return;
        SpannableString spanStr = new SpannableString(str);
        spanStr.setSpan(new ForegroundColorSpan(Color.parseColor("##FE6D11")), 0, firstEndIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spanStr);
    }

    // 设置分享部分的图片及布局
    private void setSharePart(int baseSize, int shareMarginL, int shareMarginB, int shareGap) {
        mWeChat.setTag(WE_CHAT);
        mFriends.setTag(WE_CIRCLE);
        mQQ.setTag(QQ);
        mQQSpace.setTag(QQ_ZONE);
        mWeChat.setImageResource(R.drawable.umeng_socialize_wechat);
        mFriends.setImageResource(R.drawable.umeng_socialize_wxcircle);
        mQQ.setImageResource(R.drawable.umeng_socialize_qq_on);
        mQQSpace.setImageResource(R.drawable.umeng_socialize_qzone_on);
        ArrayList<View> views = new ArrayList<>();
        views.add(mWeChat);
        views.add(mFriends);
        views.add(mQQ);
        views.add(mQQSpace);
        sharePartLayout(views, baseSize, shareMarginL, shareMarginB, shareGap);
    }

    // 获取margin值
    private RectF getMarinParams(float l, float t, float r, float b) {
        RectF rect = new RectF();
        rect.left = l;
        rect.top = t;
        rect.right = r;
        rect.bottom = b;
        return rect;
    }

    // 执行动态布局
    private void adjustLayout(View view, int w, int h, RectF marginF, int alignType) {
        if (view == null) return;
        int l = (int) marginF.left;
        int t = (int) marginF.top;
        int r = (int) marginF.right;
        int b = (int) marginF.bottom;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h);
        switch (alignType) {
            case ALIGN_L_B:
                params.addRule(RelativeLayout.ALIGN_LEFT, mBaseId);
                params.addRule(RelativeLayout.ALIGN_BOTTOM, mBaseId);
                break;
            case ALIGN_L_T:
                params.addRule(RelativeLayout.ALIGN_LEFT, mBaseId);
                params.addRule(RelativeLayout.ALIGN_TOP, mBaseId);
                break;
            case ALIGN_R_B:
                params.addRule(RelativeLayout.ALIGN_RIGHT, mBaseId);
                params.addRule(RelativeLayout.ALIGN_BOTTOM, mBaseId);
                break;
            case ALIGN_R_T:
                params.addRule(RelativeLayout.ALIGN_RIGHT, mBaseId);
                params.addRule(RelativeLayout.ALIGN_TOP, mBaseId);
                break;
            case ALIGN_T:
                params.addRule(RelativeLayout.ALIGN_TOP, mBaseId);
            case CENTER_IN_PARENT:
                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                break;
        }
        params.setMargins(l, t, r, b);
        view.setLayoutParams(params);
    }

    private void sharePartLayout(ArrayList<View> views, int baseSize, int baseMarginL, int baseMarginB, int gap) {
        int l = baseMarginL;
        for (View v : views) {
            adjustLayout(v, baseSize, baseSize, getMarinParams(l, 0, 0, baseMarginB), ALIGN_L_B);
            l += gap;
        }
    }

    /**
     * 获取基本设备信息
     * @return DeviceParams对象
     */
    private DisplayMetrics getDevicesInfo(Context context) {
        if (context == null) return null;
        Configuration config = context.getResources().getConfiguration();
        if (mOri == -1 || mOri != config.orientation) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            mMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(mMetrics);
            mOri = config.orientation;
        }
        return mMetrics;
    }

    public void setSrc(Uri uri) {
        // TODO: 2017/7/7
        switch (mCurType) {
            case ONE_PIC:
                mMidImg.setImageURI(uri);
                break;
            case TWO_PIC:
                mContentL.setImageURI(uri);
                break;
        }
    }

    public void showDialog() {
        this.setVisibility(View.VISIBLE);
    }

    public void dismissDialog() {
        this.setVisibility(View.INVISIBLE);
        resetSelected();
    }

    @Override
    public void onClick(View v) {
        if (this.getVisibility() == View.INVISIBLE) return;
        int tag = (int) v.getTag();
        switch (tag) {
            case CLOSE:
                dismissDialog();
                break;
            case BOOK_POSTER:
                mPosterType = tag;
                mRectL.setImageResource(R.drawable.dialog_dash_rect_selected);
                mRectR.setImageResource(R.drawable.dialog_dash_rect);
                mSelectedL.setVisibility(View.VISIBLE);
                mSelectedR.setVisibility(View.INVISIBLE);
                break;
            case RED_PACKET:
                mPosterType = tag;
                mRectR.setImageResource(R.drawable.dialog_dash_rect_selected);
                mRectL.setImageResource(R.drawable.dialog_dash_rect);
                mSelectedL.setVisibility(View.INVISIBLE);
                mSelectedR.setVisibility(View.VISIBLE);
                break;
            case WE_CHAT:
            case WE_CIRCLE:
            case QQ:
            case QQ_ZONE:
                if (mListener != null) mListener.onClickShare(tag, mPosterType);
                Toast.makeText(mContext, "share type---" + tag + "choose type is" + mPosterType, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void setOnDialogClickListener(OnDialogClickListener listener) {
        mListener = listener;
    }

    public interface OnDialogClickListener {
        /**
         * 点击分享区域图标
         * @param shareType 分享图标的类型 微信/朋友圈/QQ/QQ空间
         * @param posterType 选中分享的海报类型：图书/红包
         */
        void onClickShare(int shareType, int posterType);
    }
}
